/**
 * ...
 * @author Franco Ponticelli
 */

package uform.ui.comp;
import uform.property.IProperty;
import uform.property.Property;
import uform.ui.comp.Container;
import uform.ui.comp.StackItem;
import uform.ui.comp.Component;
import hxevents.Dispatcher;

class Stack extends ReadStack
{
	public function addItem(item : StackItem) : StackItem
	{
		return insertItem(length, item);
	}

	override function _id() : String
	{
		return "S";
	}
	
	public function insert(index : Int, component : Component) : StackItem
	{
		var p = component.parent.get();
		if (null != p && Std.is(p, StackItem) && !p.parent.isNull())
		{                        
			p.parent.get().remove(p);
		}
		var item = new StackItem(component);
		insertItem(index, item);
		return item;
	}
	
	public function insertItem(index : Int, item : StackItem) : StackItem
	{
		if (!item.parent.isNull())
		{
			item.parent.get().remove(item);
		}
		if (index < 0)
			index = 0;
		if (index >= length)
		{
			index = length;
			list.push(item);
		} else
			list.insert(index, item);
		length = list.length;
		_parentFor(item);
		onInsert.dispatch(index);
		return item;
	}
	
	public function clear()
	{
		while (list.length > 0)
			remove(list[0]);
	}

	public function add(component : Component) : StackItem
	{
		var p = component.parent.get();
		if (null != p && Std.is(p, StackItem) && !p.parent.isNull())
		{
			p.parent.get().remove(p);
		}
		var item = new StackItem(component);
		addItem(item);
		return item;
	}
	
	override function remove(component : Component)
	{
		if (null == component)
		{
			return false;
		} else if (Std.is(component, StackItem))
		{
			var item : StackItem = cast component;
			var pos = positionItem(item);
			if (pos >= 0)
			{
				list.remove(item);
				length--;
				super.remove(component);
				onRemove.dispatch({ item : item, pos : pos});
				return true;
			} else {
				return false;
			}
		} else if (!component.parent.isNull() && Std.is(component.parent.get(), StackItem)) {
			var item = component.parent.get();
			item.remove(component);
			item.dispose();
			return true;
		} else {
			return false;
		}
	}
}